<script lang="ts" setup>
  import type { CourseItem } from '@/types/course';
  import { getOperatorCourses, deleteOperatorCourse } from '@/api/operator';
  import { onMounted, ref } from 'vue';
  import CourseCard from '@/components/course-card/index.vue';
  import { useRouter } from 'vue-router';
  import { Modal } from '@arco-design/web-vue';
  import CourseAdder from './adder.vue';

  const props = defineProps<{
    operatorId: string;
  }>();

  const loading = ref(false);
  const list = ref<CourseItem[]>([]);
  const loadData = async () => {
    try {
      loading.value = true;
      const res = await getOperatorCourses(props.operatorId);
      list.value = res.data.data || [];
    } finally {
      loading.value = false;
    }
  };

  const router = useRouter();
  const goToCourseDetail = (id: number) => {
    const info = router.resolve({
      name: 'CourseDetailApp',
      query: {
        id,
      },
    });
    window.open(info.href);
  };

  onMounted(loadData);

  const adding = ref(false);
  const handleAddDone = async (shouldRefresh: boolean) => {
    if (shouldRefresh) {
      loadData();
    }
    adding.value = false;
  };

  const handleRemoveCourse = (courseId: string) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除？',
      async onBeforeOk() {
        await deleteOperatorCourse(props.operatorId, courseId);
        loadData();
      },
    });
  };
</script>

<template>
  <div>
    <div class="section-title" style="margin-bottom: 12px">
      合作球场
      <a-space style="margin-left: 20px">
        <a-button @click="adding = true">
          <template #icon><icon-plus /></template>
          添加
        </a-button>
      </a-space>
    </div>
    <div>
      <a-table
        :pagination="false"
        :data="list"
        size="small"
        :bordered="{ cell: false }"
      >
        <template #columns>
          <a-table-column title="球场" fixed="left">
            <template #cell="{ record }">
              <CourseCard :course-info="record" />
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="200" align="center">
            <template #cell="{ record }">
              <a-space>
                <a-button @click="handleRemoveCourse(record.id)">
                  删除
                </a-button>
                <a-button @click="goToCourseDetail(record.id)">
                  球场详情
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>

    <CourseAdder
      v-if="adding"
      :exclude-ids="list.map(i => i.id as string)"
      :operator-id="operatorId"
      @close="handleAddDone"
    />
  </div>
</template>
